package cn.jingyuan.swan.system.service.impl;

import cn.jingyuan.bee.fastjson.FastJsonUtils;
import cn.jingyuan.swan.cloud.core.Result;
import cn.jingyuan.swan.cloud.core.ResultUtils;
import cn.jingyuan.swan.system.service.GatewayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class GatewayServiceImpl implements GatewayService {

    @Resource
    DiscoveryClient discoveryClient;

    @Resource
    RestTemplate restTemplate;

    @Override
    public void refreshGateway(String gatewayIServerId) {
        List<ServiceInstance> gatewayInstances = discoveryClient.getInstances(gatewayIServerId);
        for (ServiceInstance instance : gatewayInstances) {
            String host = instance.getHost() + ":" + instance.getPort();
            String url = "http://" + host + "/mgt/routes-refresh";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(Collections.emptyMap(), headers);

            Result rs = restTemplate.postForObject(url, request, Result.class);

            if (ResultUtils.isError(rs)) {
                log.info("刷新网关失败 serviceId = {}，result = {}", instance.getServiceId(), FastJsonUtils.json(rs));
            } else {
                log.info("刷新网关成功 serviceId=  {}，result = {}", instance.getServiceId(), FastJsonUtils.json(rs));
            }
        }
    }

}
